package com.exploadingelephants.engine;

import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.graphics.Canvas;
import android.os.Bundle;

import com.exploadingelephants.sprite.Elephant;
import com.exploadingelephants.sprite.Sprite;
import com.exploadingelephants.views.PlaygroundView;

/**
 * @author Sandro De Zanet
 * 
 */
public class PlaygroundActivity extends Activity {
    /** List of all sprites on the playground */
    private ArrayList<Sprite> sprites;

    /** Playground View */
    PlaygroundView playgroundView;

    /** Main Game Loop */
    PlayLoopThread playLoopThread;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	sprites = new ArrayList<Sprite>();
	playgroundView = new PlaygroundView(this);
	setContentView(playgroundView);
    }

    /**
     * When view is ready we can create all sprites
     */
    public void onViewReady() {
	for (int i = 0; i < 10; i++) {
	    sprites.add(new Elephant(playgroundView, i));
	}

	playLoopThread = new PlayLoopThread(this, playgroundView);
	playLoopThread.startLoop();
	playLoopThread.start();
    }

    /**
     * Updating sprites
     * 
     * @param canvas
     */
    public void updateSprites(Canvas canvas) {
	Collections.sort(sprites);
	// Each sprite should update its own states and update itself
	for (Sprite sprite : sprites) {
	    sprite.updateSprite(canvas);
	}
    }

    /**
     * Check and act on sprite collisions
     */
    public void checkCollisions() {
	for (Sprite sprite : sprites) {
	    for (Sprite other : sprites) {
		if (!sprite.equals(other)) {
		    if (sprite.isColliding(other)) {
			sprite.collide(other);
		    }
		}
	    }
	}
    }

    /**
     * Cleaning up invisible/death sprites
     */
    public void cleanupSprites() {
	ArrayList<Sprite> visibleSprites = new ArrayList<Sprite>();
	for (Sprite sprite : sprites) {
	    if (sprite.isVisible()) {
		visibleSprites.add(sprite);
	    }
	}
	this.sprites = visibleSprites;
    }

    /**
     * Gets main game loop
     * 
     * @return the main game loop
     */
    public PlayLoopThread getPlayLoopThread() {
	return this.playLoopThread;
    }

    /**
     * If there is only one elephant left games finished
     * 
     * @return is the game finished?
     */
    public boolean isGameFinished() {
	return sprites.size() == 1;
    }

    /**
     * Pausing the game
     */
    public void pause() {
	playLoopThread.pauseGame();
    }

    /**
     * Resuming the game
     */
    public void resume() {
	playLoopThread.resumeGame();
    }

    /**
	 * 
	 */
    public void onGameFinished() {
	cleanupSprites();
	((Elephant) sprites.get(0)).explode();
    }

    @Override
    public void onDestroy() {
	super.onDestroy();
	playLoopThread.stopLoop();
    }
}
